home account info subscribe login search FAQ/help site map contact us


 
Brief Full
 Advanced
      Search
 Search Tips
To access the contents, click the chapter and section titles.

Bug Proofing Visual Basic: A Guide to Error Handling and Prevention
(Publisher: John Wiley & Sons, Inc.)
Author(s): Rod Stephens
ISBN: 0471323519
Publication Date: 11/01/98

Search this book:
 
Previous Table of Contents Next


Figure 13.4 shows Visual Basic 5’s Visual Data Manager, available in the Add-Ins menu, displaying a record from the simple error database used by program DBErr. Visual Basic 6’s Visual Data Manager is similar. The Data Manager in Visual Basic 4 is significantly different, but it provides similar features for viewing and modifying database files.


Figure 13.4  Visual Data Manager displaying error records.

Send Email

Writing error messages into files or databases are passive techniques. You must look in the file or database to find new errors. Few developers realize they can make bug notification more active by automatically sending messages to developers using electronic mail.

Program MailErr uses Microsoft’s messaging application program interface (MAPI) to send mail when it encounters an error. To send mail, the program uses the MAPISession and MAPIMessages controls. Because these are controls, they must reside on a form. The program’s MailErrorForm contains both of these controls and the SendErrorMail subroutine that uses them.

When you click the main program’s Raise Error button, the code raises a divide by zero error. An error handler catches the error and invokes the MailErrorForm’s SendErrorMail subroutine as shown in the following code.

‘ Raise an error.
Private Sub cmdRaiseError_Click()
    On Error GoTo RaiseErrorError

    ‘ Raise a divide by zero error.
     Err.Raise 11

RaiseErrorError:
    MailErrorForm.SendErrorMail “MailError.cmdRaiseError_Click”
End Sub

Subroutine SendErrorMail sets the MAPISession control’s UserName and Password properties, and then signs on to the mail system. You will need to modify the UserName and Password values for your system.

The routine then fills in the MAPIMessages control’s properties to define the message’s recipient, subject, and body text. You could modify this code to send the mail to more than one recipient.

The program then sends the mail with the Send command. It gives this command the parameter False to indicate that the control should not display a status message to the user. Finally, the subroutine signs off the mail session.

If SendErrorMail encounters an error while sending the mail, it falls back to the strategy of displaying an error message to the user. It uses MakeErrorMessage to create a new message describing the problem with the mail system and it displays both messages.

‘ Send mail to the bugs account.
Public Sub SendErrorMail(ByVal routine_name As String)
Dim txt1 As String
Dim txt2 As String

    ‘ Create the error message.
     txt1 = MakeErrorMessage(routine_name)

    On Error GoTo SendErrorMailError

    mpsErrorMail.UserName = “user@user_computer”
    mpsErrorMail.Password = “user_password”
    mpsErrorMail.SignOn

    mpmErrorMail.SessionID = mpsErrorMail.SessionID
    mpmErrorMail.Compose
    mpmErrorMail.RecipDisplayName = “Automatically Reported Bugs”
    mpmErrorMail.RecipAddress = “bugs@development_computer”
    mpmErrorMail.AddressResolveUI = False
    mpmErrorMail.MsgSubject = “Automatic Error Report”
    mpmErrorMail.MsgNoteText = txt1
    mpmErrorMail.Send False

    mpsErrorMail.SignOff

    ‘ Make sure this form is not loaded.
     Unload Me
    Exit Sub

SendErrorMailError:
    ‘ There was an error saving to the file.
    ‘ Just present the message.
    txt2 = MakeErrorMessage(“SendErrorMail”)
    MsgBox “Error mailing automatic error message.” & _
        vbCrLf & _
        “Please record the following information ” & _
        “and send it to the development team:” & _
        vbCrLf & vbCrLf & txt2 & _
        vbCrLf & vbCrLf & txt1

    ‘ Make sure this form is not loaded.
    Unload Me
    Exit Sub
End Sub

‘ Make an appropriate error message.
Public Function MakeErrorMessage(ByVal routine_name As String) As String
    MakeErrorMessage = _
        “Unexpected error ” & _
        Format$(Err.Number) & _
        “ in ” & routine_name & “.” & _
        vbCrLf & Err.Description
End Function

By sending you mail, this method bring errors to your attention promptly. If you act quickly, you may be able to diagnose and solve the problem before users are aware it exists.

Self-Test

Program Bad13, shown in Figure 13.5, uses another strategy for handling errors. It writes error messages into separate files. When the program encounters an error, subroutine SaveErrorToFile examines the files in the directory specified by the FILE_PREFIX constant. It adds successive values to the prefix filename until it finds a filename that does not yet exist. For example, the program looks for C:\Temp\err1.txt, C:\Temp\err2.txt, C:\Temp\err3.txt, and so forth until if finds a file that does not exist. The routine then opens that file and saves the error information in it.

Program Bad13 calculates the ratio of two numbers. Enter values in the two TextBoxes and click the Calculate button. The program displays the ratio of the first value to the second. Enter nonnumeric values or the value 0 for the second variable to generate errors.

The following code shows how the program calculates ratios and displays errors when it catches them. It has several problems that make it less than ideal at error handling. Look over the code and try to find ways to improve it. Appendix A, “Self-Test Solutions,” contains a better version of the program that handles errors more safely.


Figure 13.5  Program Bad13.

‘ Calculate the ratio of A / B.
Private Sub cmdCalculate_Click()
Dim A As Single
Dim B As Single
Dim A_over_B As Single

    On Error GoTo RaiseErrorError

    A = CSng(txtA.Text)
    B = CSng(txtB.Text)
    A_over_B = A / B
    lblAOverB.Caption = Format$(A_over_B, “0.000”)

RaiseErrorError:
    SaveErrorToFile _
       “Error ” & Format$(Err.number) & _
       “ in FileError.cmdRaiseError_Click.” & _
       vbCrLf & Err.Description
End Sub

‘ Append mail to an error log file.
Public Sub SaveErrorToFile(ByVal txt As String)
Const FILE_PREFIX = “C:\Errors\err”
Const FILE_SUFFIX = “.txt”
Dim file_name As String
Dim fnum As Integer
Dim trial As Integer

    On Error GoTo SaveErrorToFileError

    ‘ Find a file name we can use.
     trial = 1
    Do
         ‘ Compute the next name to try.
         file_name = FILE_PREFIX & _
             Format$(trial) & FILE_SUFFIX

         ‘ See if the file exists.
         If Dir(file_name) = “” Then Exit Do.
         trial = trial + 1
    Loop

    ‘ Open the file.
     fnum = FreeFile
    Open file_name For Append As #fnum

    ‘ Write the date and time, and the error message.
     Print #fnum, Now, txt, “**********”

    ‘ Close the file.
     Close #fnum
    Exit Sub

SaveErrorToFileError:
    ‘ There was an error saving to the file.
    ‘ Just display the message.
     MsgBox txt
    Exit Sub
End Sub

Summary

The following Bug Stoppers summarize the standard error management code described in this chapter. Combined with the concepts explained in Chapter 12, “Error Handling Fundamentals,” these provide formidable protection against all sorts of unanticipated problems.

BUG STOPPERS: standard error handlers
Use a systematic approach.
Handle error events raised by controls.
Present error messages to the user.
Use stack unwinding error handlers.
Save errors in a file.
Save errors in a database.
Send electronic error mail.


Previous Table of Contents Next


Products |  Contact Us |  About Us |  Privacy  |  Ad Info  |  Home

Use of this site is subject to certain Terms & Conditions, Copyright © 1996-1999 EarthWeb Inc.
All rights reserved. Reproduction whole or in part in any form or medium without express written permision of EarthWeb is prohibited.